package com.phcx.corporate.controller;

import com.phcx.corporate.json.request.ReqMessage;
import com.phcx.corporate.json.request.ReqMessageContent;
import com.phcx.corporate.json.request.ReqMessageHeader;
import com.phcx.corporate.json.response.ResMessage;
import com.phcx.corporate.json.response.ResMessageContent;
import com.phcx.corporate.json.response.ResMessageHeader;
import com.phcx.corporate.model.*;
import com.phcx.corporate.service.BizLogContentService;
import com.phcx.corporate.service.BizLogService;
import com.phcx.corporate.utils.CodeAuthUtil;
import com.phcx.corporate.utils.HttpUtils;
import com.phcx.corporate.utils.SessionUtil;
import com.phcx.corporate.utils.TableUtil;
import com.phcx.corporate.vo.CorporateVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;

/*
 * @Author: zmh
 * @Date: 2023/05/17/11:20
 * @Description: 获取企业码接口、查询与打印企业码权限控制
 */

@Slf4j
@CrossOrigin
@RestController
@RequestMapping("/corporate")
public class CorporateCodeController {

    @Value("${syscode}")
    private String syscode;

    @Value("${authcode}")
    private String authcode;

    @Value("${address}")
    private String address;

    @Autowired
    private BizLogContentService bizLogContentService;

    @Autowired
    private BizLogService bizLogService;

    private String bizLogId = null;

    private BizLog bizLog = new BizLog();


    /**
     * 获取企业码接口
     *
     * @param licence13 统一社会信用代码
     */
    @GetMapping("/getCode/{licence13}")
    public Result<CorporateVo> getAuth(@PathVariable String licence13, HttpServletRequest request) throws IOException {

        CorporateVo corporateVo = null;

        // session校验
        AdminInfo adminInfo1 = SessionUtil.sessionExpiration(request);
        if (adminInfo1 == null){
            return Result.fail();
        }
        if (!(licence13.startsWith("9"))||licence13.length()!=18) {
            return Result.fail();
        }
        request.getSession().removeAttribute("bizLogId");
        licence13 = licence13.trim().toUpperCase();

        AdminInfo admin = (AdminInfo) request.getSession().getAttribute("admin");
        RegOffice regOffice = (RegOffice) request.getSession().getAttribute("regInfo");
        String adminLicence42Code = regOffice.getLicence42Code();       // 管理员所属登记机关代码
        String adminLicence42 = regOffice.getLicence42();               // 管理员所属登记机关名称

        // 地区代码 与 管理员所属登记机关代码 比对
        boolean codeAuth = CodeAuthUtil.getCodeAuthByLicence13(licence13, adminLicence42Code);

        HashMap<String, String> result = getCorporateCode(licence13);
        String errorCode = result.get("errorCode");                 // 错误代码
        String errorInfo = result.get("errorInfo");                 // 错误信息
        String qrImage = result.get("qrImage");                     // 二维码
        String entName = result.get("entName");                     // 企业名称
        String corporateOrgCode = result.get("corporateOrgCode");   // 企业的所属登记机关代码
        String corporateOrgName = result.get("corporateOrgName");   // 所属登记机关名称

        // 地区代码比对失败 使用接口返回的 企业所属登记机关代码、名称 与 管理员所属登记机关代码、名称 比对
        if(!codeAuth){
            if(corporateOrgCode == null)
                corporateOrgCode = "";
            if(corporateOrgName == null)
                corporateOrgName = "";
            codeAuth = CodeAuthUtil.getCodeAuthByInterface(adminLicence42Code, adminLicence42, corporateOrgCode, corporateOrgName);
        }

        if ((!errorCode.equals("0")) || codeAuth){
            // 返回错误信息
            if (!errorCode.equals("0")) {
                corporateVo = new CorporateVo("没有企业信息",errorInfo);
                return Result.ok(corporateVo);
            }

            // 保存查询企业码日志
            request.getSession().setAttribute("licence13",licence13);
            request.getSession().setAttribute("bizLogId",bizLogId);
            bizLog.setAdminId(admin.getAdminId());
            bizLog.setUsername(admin.getUsername());
            bizLog.setLicence18(result.get("entName"));
            bizLogService.save(bizLog);
            log.info("[保存企业码查询日志]");

            // 返回企业码、名称
            corporateVo = new CorporateVo(qrImage, entName);
            return Result.ok(corporateVo);
        }
        // 没有权限
        corporateVo = new CorporateVo("权限不足","权限不足。请输入 "+adminLicence42+"("+adminLicence42Code+")  登记机关管辖内企业信息");
        return Result.ok(corporateVo);
    }

    // 调用省局接口，获取企业码
    private HashMap<String, String> getCorporateCode(String licence13) throws IOException {
        String url = "http://" + address + "/authLicenceCode/licencecodereg.do";

        ReqMessageHeader reqMessageHeader = ReqMessageHeader.builder()
                .businesstype("208")
                .syscode(syscode)
                .authcode(authcode)
                .sign("")
                .version("1").build();
        ReqMessageContent reqMessageContent = ReqMessageContent.builder()
                .orgcode(licence13)
                .entname("")
                .color("1")
                .opertime("").build();
        ReqMessage reqMessage = new ReqMessage(reqMessageHeader, reqMessageContent);

        // 根据统一社会信用代码获取企业码
        ResMessage resMessage = HttpUtils.post(url, reqMessage, ResMessage.class);

        // 保存请求与响应报文
        bizLogId = TableUtil.getID();
        BizLogContent bizLogContent = new BizLogContent(bizLogId, reqMessage.toString(), resMessage.toString());
        bizLogContentService.save(bizLogContent);

        // 设置查询企业码日志
        bizLog.setLogId(bizLogId);
        bizLog.setBizType("0");
        bizLog.setLicence18("");
        bizLog.setLicence13(licence13);
        bizLog.setErrorCode(resMessage.getMessage_header().getErrorCode());
        bizLog.setErrorInfo(resMessage.getMessage_header().getErrorInfo());
        bizLog.setLogDate(TableUtil.getLogTime());

        // 返回获取结果
        ResMessageHeader header = resMessage.getMessage_header();
        ResMessageContent content = resMessage.getMessage_content();

        log.info("[调用获取企业码接口]");
        HashMap<String, String> result = new HashMap<>();
        result.put("errorCode", header.getErrorCode());               // 错误代码
        result.put("errorInfo", header.getErrorInfo());               // 错误信息
        result.put("qrImage", content.getQrimage_o());                // 二维码
        result.put("entName", content.getEntname());                  // 企业名称
        result.put("corporateOrgCode", content.getRegorg_cn_code());  // 企业的所属登记机关代码
        result.put("corporateOrgName", content.getRegorg_cn());       // 所属登记机关名称
        return result;
    }

    @RequestMapping("/sessionExpiration")
    public Result<?> isSessionExpiration(HttpServletRequest request){
        log.info("session验证");
        AdminInfo adminInfo = SessionUtil.sessionExpiration(request);
        if (adminInfo == null){
            return Result.fail("session过期");
        }
        return Result.ok();
    }
}
